// pages/mine/second_page/money.js
var App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    moneyTotal: '0.00',
    rechargeList: [],
    rechargePrice: '', //输入的充值金额
    rechargeAmount: '', //实际充值金额
    payment: false,
    choseItem: {},
    // showPop: false,
    hasPhone:false //是否有手机号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      moneyTotal: options.total == undefined ? '0.00' : parseFloat(options.total).toFixed(2)
    })
    this.getMoneyMsg();
  },

  onShow:function(){
    let info = wx.getStorageSync('userInfo')
    if (info.phone == '0' || info.phone == 0) {//没有手机号
      this.setData({
        hasPhone: false
      })
    } else {
      this.setData({
        hasPhone: true
      })
    }
  },

  onReady:function(){

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //back
  backLastPage: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  // 充值选择
  choseRechartMode: function(e) {
    let index = e.currentTarget.dataset.index;
    var arr = this.data.rechargeList;
    for (var i = 0; i < arr.length; i++) {
      arr[i].choseItem = false;
    }
    arr[index].choseItem = true;
    this.setData({
      rechargeList: arr,
      rechargePrice: arr[index].money,
      choseItem: arr[index],
      rechargeAmount: arr[index].money
    })
  },
  // 输入金额
  onRechargeInput: function(e) {
    var arr = this.data.rechargeList;
    for (var i = 0; i < arr.length; i++) {
      arr[i].choseItem = false;
    }
    this.setData({
      rechargeList: arr,
      rechargePrice: e.detail.value,
      rechargeAmount: e.detail.value,
      choseItem: {}
    })
  },
  //立即充值
  onRechartHandle: function(e) {
    let that = this;
    let amount = that.data.rechargeAmount;
    let msg = wx.getStorageSync('userInfo');
    if (msg.phone == '0' || msg.phone == '') {

      if (e.detail.errMsg == 'getPhoneNumber:ok') {//同意手机号授权
        wx.request({
          url: App.data.globalAPI + '/users/weixin/decrypt',
          data: {
            token: wx.getStorageSync('token'),
            data: e.detail.encryptedData,
            iv: e.detail.iv
          },
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if (res.data.error == 0) {
              var myphone = JSON.parse(res.data.data).phoneNumber;

              let userInfo = wx.getStorageSync('userInfo');
              let allUserMsg = wx.getStorageSync('allUserMsg');
              userInfo.phone = myphone;
              allUserMsg.userinfo = userInfo;
              wx.setStorageSync('userInfo', userInfo);
              wx.setStorageSync('allUserMsg', allUserMsg);

              that.uploadUserMsg();
              that.setData({
                hasPhone:true
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 800
              })
            }
          },fail(res){
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '网络异常，请稍后重试！',
              showCancel: false,
              success(res) {
              }
            })
          }
        })
      }
      return;
    }
    if (amount == '') {
      wx.showToast({
        title: '请输入充值金额',
        icon: 'none',
        duration: 800
      })
    } else if (parseFloat(amount) < 1) {
      wx.showToast({
        title: '最低储值1元哦!',
        icon: 'none',
        duration: 800
      })
    } else {
      that.setData({
        payment: true
      })
    }
  },

  //提交用户手机
  uploadUserMsg: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/bindphone',
      data: {
        token: wx.getStorageSync('token'),
        phone: wx.getStorageSync('userInfo').phone,
        validate_code: '0000',
        is_activity: (App.data.activeCity.indexOf(wx.getStorageSync('schoolId')) > -1) ? 1 : 0
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        const arr = res.data;
        if (arr.error != 0) {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        } else if (arr.error == 0){
          that.onRechartHandle();
        }

        if (Object.keys(arr.data).length > 0) { //以前有盒子
          wx.showToast({
            title: '信息同步成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/index/index',
            })
          }, 1000)
        } else if (App.data.locationIsActive) {//是参加活动的地区
          wx.showToast({
            title: '优惠券发放成功请到券包查看',
            icon: 'none',
            duration: 1000
          })
        }
        
      }
    })
  },

  // 显示支付方式弹窗
  showPayModal: function() {
    this.setData({
      payment: false
    })
  },
  stopHandle: function() {
    return false;
  },
  // 确认支付
  onPaymentHandle: function() {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/recharge/pay',
      data: {
        token: wx.getStorageSync('token'),
        money: that.data.rechargeAmount,
        coupon_id: that.data.choseItem.id == undefined ? '' : that.data.choseItem.id,
        pay_method: 'wxlite'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == "100009") {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 600
          })
          setTimeout(function() {
            wx.reLaunch({
              url: '/pages/index/index'
            })
          })
        } else if (res.data.error == 0) {
          var payArr = res.data.data.pay;
          wx.requestPayment({
            timeStamp: payArr.timeStamp,
            nonceStr: payArr.nonceStr,
            package: payArr.package,
            signType: payArr.signType,
            paySign: payArr.paySign,
            success(res) {
              wx.showToast({
                title: '充值成功',
              })
              //重置页面
              var arr = that.data.rechargeList;
              for (var i = 0; i < arr.length; i++) {
                arr[i].choseItem = false;
              }
              let newMoney = parseFloat(that.data.moneyTotal) + parseFloat(that.data.rechargeAmount);
              that.setData({
                rechargeList: arr,
                rechargePrice: '', //输入的充值金额
                rechargeAmount: '', //实际充值金额
                // moneyTotal: parseFloat(newMoney).toFixed(2),
                payment: false,
              })
              that.getMoneyTotal();
            },
            fail(res) {
              wx.showToast({
                title: '充值失败，请稍后重试',
                icon: 'none'
              })
            }
          })
        } else if (res.data.error == 'openId 错误') {
          wx.showToast({
            title: '网络异常，稍后重试',
            icon: 'none',
            duration: 600
          })
          App.getWxUserinfo()
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 600
          })
        }
      }, fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })

  },
  //获取钱包信息
  getMoneyMsg: function() {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/recharge/coupon',
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          let list = res.data.data;
          for (var i = 0; i < list.length; i++) {
            list[i].choseItem = false;
          }
          that.setData({
            rechargeList: list
          })
          wx.hideLoading();
        }
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
            wx.reLaunch({
              url: '../index/index',
            })
          }
        })
      }
    })
  },
  //清空输入内容
  clearInputMsg: function() {
    let price = this.data.rechargePrice;
    if (price != '') {
      this.setData({
        rechargePrice: '',
        choseItem: {}
      })
      var arr = this.data.rechargeList;
      for (var i = 0; i < arr.length; i++) {
        arr[i].choseItem = false;
      }
      this.setData({
        rechargeList: arr,
        rechargePrice: '', //输入的充值金额
        rechargeAmount: '', //实际充值金额
        payment: false,
      })
    }
  },
  //钱包金额
  getMoneyTotal: function() {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/wallet/info',
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          // parseFloat(res.data.data.money).toFixed(2)
          that.setData({
            moneyTotal: res.data.data.money
          })
        }
      }
    })
  }
})